<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;
use K12SSO_Factory;
use Kris\LaravelFormBuilder\FormBuilderTrait;
use App\Common\Utils\JsonResponse;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests, FormBuilderTrait;

    // 登录成功之后跳转地址的 session 名
    const SESS_REDIRECT_AUTHENTICATED = 'redirect_authenticated';

    /**
     * 与中心 UAC 关联参数设置
     */
    protected $links = [];

    /** @var \App\Services\Link */
    protected $link = null;

    /** @var \K12SSO_UAC */
    private static $uac = null;

    public function __construct()
    {
        $this->link     = app('link');
        $this->links    = $this->link->getLinkData();
        // 设置全局视图变量
        View::share([
            'links'    => $this->links,
            'center_base_url' => $this->getCenterBaseUrl(),
        ]);
    }

    protected function error(\Exception $e){
        Log::error($e);
        return JsonResponse::error($e->getMessage());   // 失败
    }

    /**
     * 获取单点登录 UAC 对象实例
     * 
     * @return \K12SSO_UAC
     */
    protected function getUac()
    {

        $options = [
            'base_url'     => $this->getCenterBaseUrl(),
            'xmlrpc_host'  => $this->links['center_host'],
            'xmlrpc_port'  => $this->links['center_port'],
            'xmlrpc_path'  => $this->links['center_sso_path'],
            'xmlrpc_user'  => $this->links['center_sso_user'],
            'xmlrpc_pass'  => $this->links['center_sso_pass'],
            'xmlrpc_debug' => env('CENTER_UAC_DEBUG', 0),
            'encoding'     => $this->links['center_encoding'],
        ];
        return K12SSO_Factory::createInstance(K12SSO_Factory::TYPE_UAC, $options);
    }

    /**
     * 获取中心平台基础 URL
     * 
     * @return string
     */
    protected function getCenterBaseUrl()
    {
        $base_url = '';
        if ($this->links['center_port'] == 443) {
            $base_url .= 'https';
        } else {
            $base_url .= 'http';
        }
        $base_url .= '://'.$this->links['center_host'];
        if ($this->links['center_port'] != 80 && $this->links['center_port'] != 443) {
            $base_url .= ':'.$this->links['center_port'];
        }
        $base_url .= '/platform/';
        return $base_url;
    }
}
